package com.suxiaofang.library.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.suxiaofang.library.common.Result;
import com.suxiaofang.library.entity.Category;
import com.suxiaofang.library.service.impl.CategoryServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 文件名：Category
 * 创建者：蔡江鸿
 * 创建时间：2022/9/16-18:58
 * 描述：
 */
@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryServiceImpl categoryService;


    /**
     * 新增和更新
     *
     * @param category
     * @return
     */
    @PostMapping
    public Result save(@RequestBody Category category) {
        return Result.success(categoryService.saveOrUpdate(category));
    }
    /**
     * 查询所有
     *
     * @return
     */
    @GetMapping
    public Result findAll() {
        return Result.success(categoryService.list());
    }



    @GetMapping("/count")
    public Result userCount(){
        return Result.success(categoryService.count());
    }

    /**
     * 根据id删除
     *
     * @param id
     * @return
     */
    @DeleteMapping("{id}")
    public Result delete(@PathVariable Integer id) {
        return Result.success(categoryService.removeById(id));
    }


    /**
     * 根据id
     *
     * @param id
     * @return
     */
    @GetMapping ("{id}")
    public Result find(@PathVariable Integer id) {
        return Result.success(categoryService.getById(id));
    }
    /**
     * 分页查询
     * mybatis-plus 查询
     * //        @RequestParam(defaultValue = "") String nickname
     * //        queryWrapper.or().like(!Strings.isEmpty(nickname),"nickname", nickname);
     *
     * @return
     * @RequestParam Limit第-个参数.=(pageNum-1)*pageSize
     */
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(defaultValue = "") String name
    ) {
        IPage<Category> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(!Strings.isEmpty(name),"name", name);
        queryWrapper.orderByAsc("id");
        return Result.success(categoryService.page(page, queryWrapper));
    }


}
